package com.elm.controller;

import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.elm.entity.User;
import com.elm.service.UserService;
import com.elm.service.impl.UserServiceImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

public class UserController implements BaseController{
    //业务逻辑层的类
    private UserService userService;
    public UserController() {
        userService = new UserServiceImpl();
    }

    //根据请求选择不同的方法处理
    @Override
    public void handleRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 解析请求动作
        String action = req.getPathInfo().split("/")[2];

        switch (action) {
            case "saveUser":
                doSaveUser(req, resp);
                break;
            case "getUserById":
                doGetUserById(req, resp);
                break;
            case "getUserByIdByPass":
                doGetUserByIdByPass(req, resp);
                break;

        }
    }

    private void doSaveUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //转化为相应的User类
        User user = new User();
        user.setUserSex(Integer.valueOf(req.getParameter("userSex")));
        user.setUserName(req.getParameter("userName"));
        user.setUserId(req.getParameter("userId"));
        user.setPassword(req.getParameter("password"));
        int result = userService.saveUser(user);

        resp.setContentType("application/json;charset=UTF-8");
        resp.getWriter().write(new Gson().toJson(result));
    }

    private void doGetUserById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userId = req.getParameter("userId");

        int result = userService.getUserById(userId);

        resp.setContentType("application/json;charset=UTF-8");
        if (result == 0) {
            resp.getWriter().write("{\"error\":\"用户不存在\"}");
        }else {

            resp.getWriter().write(new Gson().toJson(result));
        }
    }

    private void doGetUserByIdByPass(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userId = req.getParameter("userId");
        String pas = req.getParameter("password");

        User user = userService.getUserByIdByPass(userId, pas);

        // 3. 返回JSON响应
        resp.setContentType("application/json;charset=UTF-8");
        if (user != null) {
            resp.getWriter().write(new Gson().toJson(user));
        } else {
            resp.getWriter().write("{\"error\":\"账号或密码错误\"}");
        }
    }
}
